#include "main.h"
#include "stdio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "ff.h"
#include "diskio.h"


#include "swd_host.h"
#include "swd_download_file.h"
#define TAG "app_downalder"
#include <unistd.h>
#define TASK_STACK_SIZE 2048
#define TASK_PRIORITY 10

static char current_dir[128] = "/"; // 全局变量存储当前目录，根目录为/sdcard

void app_downalder_task(void *arg)
{
    swd_init_debug();
    uint32_t val = 0;
    while (1)
    {
        // swd_read_dp(0x00, &val);
        // printf("Chip IDCODE: %08lx\n", val);
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}

void app_downalder_init(void)
{
    printf("当前目录: %s\n", current_dir);
    xTaskCreate(app_downalder_task, "app_downalder_task", TASK_STACK_SIZE, NULL, TASK_PRIORITY, NULL);
}

void read_idcode(void)
{
    // uint32_t idcode = 0;
    // swd_read_dp(0x00, &idcode);
    // printf("IDCODE: %08lx\n", idcode);
    swd_download_update_flash_algo("/sdcard/flash/STM32F10x_128.FLM");
    printf("update flash algo success\n");
    swd_download_from_file("/sdcard/d/Project.bin");
}
// swd_download_from_file("/sdcard/d/2_500MS.bin.bin");
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0) | SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC) | SHELL_CMD_DISABLE_RETURN,
                 read_idcode, read_idcode, "read idcode");

void list_dir(const char *path)
{
    char full_path[256] = {0};

    // 处理相对路径
    if (path[0] != '/')
    {
        snprintf(full_path, sizeof(full_path), "%s/%s", current_dir, path);
    }
    else
    {
        strncpy(full_path, path, sizeof(full_path));
    }

    ESP_LOGI(TAG, "Listing files in %s:", full_path);

    FF_DIR dir;
    FILINFO fno;
    FRESULT res = f_opendir(&dir, full_path);
    if (res != FR_OK)
    {
        ESP_LOGE(TAG, "无法打开目录: %s (错误码: %d)", full_path, res);
        return;
    }

    printf("%s:\n", path[0] ? path : ".");
    while (1)
    {
        res = f_readdir(&dir, &fno);
        if (res != FR_OK || fno.fname[0] == 0)
        {
            break;
        }
        printf("    %s: %s\n",
               (fno.fattrib & AM_DIR) ? "directory" : "file     ",
               fno.fname);
    }
    f_closedir(&dir);
}
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0) | SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC) | SHELL_CMD_DISABLE_RETURN,
                 ls, list_dir, "list directory");

void downalder_file(const char *path)
{
    char file_path[256] = {0};
    snprintf(file_path, sizeof(file_path), "/sdcard/d/%s", path);

    FIL file;
    FRESULT res = f_open(&file, file_path, FA_READ);
    if (res != FR_OK)
    {
        ESP_LOGE(TAG, "无法打开文件: %s (错误码: %d)", file_path, res);
        return;
    }

    swd_download_update_flash_algo("/sdcard/flash/STM32F10x_128.FLM");
    // 这里需要根据实际需求实现文件下载逻辑
    // 示例: 读取文件内容并处理
    char buffer[256];
    UINT bytes_read;
    while (f_read(&file, buffer, sizeof(buffer), &bytes_read) == FR_OK && bytes_read > 0)
    {
        // 处理文件内容
    }

    f_close(&file);
    swd_download_from_file(file_path); // 保持原有调用
}
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0) | SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC) | SHELL_CMD_DISABLE_RETURN,
                 downalder_file, downalder_file, "downalder file");

void change_dir(const char *path)
{
    char new_path[256] = {0};
    FRESULT res;
    FF_DIR dir;

    // 处理相对路径
    if (path[0] != '/')
    {
        snprintf(new_path, sizeof(new_path), "%s/%s", current_dir, path);
    }
    else
    {
        strncpy(new_path, path, sizeof(new_path));
    }

    // 检查目录是否存在
    res = f_opendir(&dir, new_path);
    if (res != FR_OK)
    {
        ESP_LOGE(TAG, "目录不存在或无法访问: %s (错误码: %d)", new_path, res);
        return;
    }
    f_closedir(&dir);

    // 切换目录
    res = f_chdir(new_path);
    if (res == FR_OK)
    {
        strncpy(current_dir, new_path, sizeof(current_dir));
        ESP_LOGI(TAG, "当前目录已切换到: %s", current_dir);
    }
    else
    {
        ESP_LOGE(TAG, "切换目录失败: %s (错误码: %d)", new_path, res);
    }
}
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0) | SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC) | SHELL_CMD_DISABLE_RETURN,
                 cd, change_dir, "change directory");

void print_working_dir(void)
{
    printf("当前目录: %s\n", current_dir);
}
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0) | SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC) | SHELL_CMD_DISABLE_RETURN,
                 pwd, print_working_dir, "print working directory");
